package com.qidianit.mes.pro.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidianit.mes.pojo.pro.Process;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.pro.WorkflowProcess;
import com.qidianit.mes.pro.mapper.DictDataMapper;
import com.qidianit.mes.pro.mapper.ProcessMapper;
import com.qidianit.mes.pro.mapper.WorkflowProcessMapper;
import com.qidianit.mes.pro.service.WorkflowProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: YKYB
 * @Date: 2025/9/18 21:36
 * @Description:
 */
@Service
public class WorkflowProcessServiceImpl implements WorkflowProcessService {

    @Autowired
    private WorkflowProcessMapper workflowProcessMapper;
    @Autowired
    private ProcessMapper processMapper;

    @Autowired
    private DictDataMapper dictDataMapper;

    @Override
    public Result<PageInfo<WorkflowProcess>> selectList(Long workflowId, Integer page, Integer size) {
        //开启分页
        PageHelper.startPage(page, size);
        // 查询关系对象列表
        List<WorkflowProcess> workflowProcesses = workflowProcessMapper.selectList(workflowId);
        // 遍历组织数据
        for (WorkflowProcess wp : workflowProcesses) {
            // 查询当前工序
            wp.setProcess(processMapper.selectById(wp.getProcessId()));
            // 查询下一道工序
            // 查询当前工艺的所有工序 按照序号顺序排序。  根据当前工序找到当前工序的下一道工序。
            // 查询当前工序的所有工序
            List<Process> processes = processMapper.selectProcessByWorkflowId(wp.getWorkflowId());
            Process nextProcess = getNextProcess(processes, wp.getProcess());
            wp.setNextProcess(nextProcess);
            // 查询与下一道工序关系的字典信息
            wp.setRelationNextDict(dictDataMapper.selectById(wp.getRelationNext()));
        }
        return Result.success(new PageInfo<>(workflowProcesses));
    }

    //新增工序组成
    @Override
    public Result<WorkflowProcess> add(WorkflowProcess wp) {
        //  序号重复
        Wrapper<WorkflowProcess> orderWrap = new QueryWrapper<WorkflowProcess>()
                .eq("workflow_id", wp.getWorkflowId())
                .eq("step_order", wp.getStepOrder())
                .eq("delete_flag", 0);
        if (workflowProcessMapper.equals(orderWrap)) {
            return Result.error("工序序号[" + wp.getStepOrder() + "]已经存在");
        }
        //工序重复
        Wrapper<WorkflowProcess> procWrap = new QueryWrapper<WorkflowProcess>()
                .eq("workflow_id", wp.getWorkflowId())
                .eq("process_id", wp.getProcessId())
                .eq("delete_flag", 0);
        if (workflowProcessMapper.equals(procWrap)) {
            Process p = processMapper.selectById(wp.getProcessId());
            String name = p == null ? "" : p.getProcessName();
            return Result.error("工序" + name + "已经存在");
        }

        wp.setCreateBy("system");   // 当前登录人可后续替换
        workflowProcessMapper.insert(wp);
        return Result.success(null);
    }

    //根据id查询工艺工序组成
    @Override
    public Result<WorkflowProcess> selectById(Long id) {
        WorkflowProcess wp = workflowProcessMapper.selectById(id);
        if (wp == null) {
            return Result.error("记录不存在或者删除");
        }
        //当前工序
        wp.setProcess(processMapper.selectById(wp.getProcessId()));
        //下一道工序
        List<Process> processes = processMapper.selectProcessByWorkflowId(wp.getWorkflowId());
        wp.setNextProcess(getNextProcess(processes, wp.getProcess()));
        //字典
        if (wp.getRelationNext() != null) {
            wp.setRelationNextDict(dictDataMapper.selectById(wp.getRelationNext()));
        }
        return Result.success(wp);
    }

    //编辑工艺的工序组成
    @Override
    public Result<WorkflowProcess> update(WorkflowProcess wp) {
        Wrapper<WorkflowProcess> orderWrap = new QueryWrapper<WorkflowProcess>()
                .eq("workflow_id", wp.getWorkflowId())
                .eq("step_order", wp.getStepOrder())
                .eq("id", wp.getId())
                .eq("delete_flag", 0);
        if (workflowProcessMapper.equals(orderWrap)) {
            return Result.error("工单序号[" + wp.getStepOrder() + "]已经存在");
        }
        //工单重复校验
        Wrapper<WorkflowProcess> procWrap = new QueryWrapper<WorkflowProcess>()
                .eq("workflow_id", wp.getWorkflowId())
                .eq("step_order", wp.getStepOrder())
                .eq("id", wp.getId())
                .eq("delete_flag", 0);
        if (workflowProcessMapper.equals(procWrap)) {
            Process p = processMapper.selectById(wp.getProcessId());
            String name = p == null ? "" : p.getProcessName();
            return Result.error("工序" + name + "已经存在");
        }
        //执行更新
        int rows = workflowProcessMapper.update(wp);
        return rows == 1 ? Result.success(null) : Result.error("操作失败");
    }

    //根据工艺的工序组成编号删除单个工序组成
    @Override
    @Transactional
    public Result<?> deleteById(Long id) {
        int process = workflowProcessMapper.deleteById(id);
        return process > 0 ? Result.error("删除失败") : Result.success("删除成功");

    }

    //批量删除工艺的工序组成
    @Override
    @Transactional
    public Result<?> batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的工序组成");
        }
        int rows = workflowProcessMapper.batchDelete(ids);
        return rows > 0 ? Result.success(null) : Result.error("操作失败");
    }


    /**
     * @param processes
     * @param process
     * @return
     */
    private Process getNextProcess(List<Process> processes, Process process) {
        // 从processes 找到 process 的下一道工序，如果没有就返回null。
        for (int i = 0; i < processes.size() - 1; i++) {
            if (processes.get(i).getId().equals(process.getId()) && processes.get(i + 1) != null) {
                return processes.get(i + 1);
            }
        }
        return null;
    }
}

